package com.walle.gatewayserver.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.walle.gatewayserver.base.CodeContant;
import com.walle.gatewayserver.properties.TokenVerificationProperties;
import com.walle.gatewayserver.service.ITokenService;
import com.walle.gatewayserver.utils.GetParamsUtil;
import com.walle.gatewayserver.vo.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
@Slf4j
@Component
public class AuthFilter extends ZuulFilter {
	
	@Autowired
    private TokenVerificationProperties tokenProperties;
	@Autowired
	private ITokenService tokenService;
	
	@Override
	public Object run() throws ZuulException {
		
		RequestContext ctx = RequestContext.getCurrentContext();
		HttpServletRequest request = ctx.getRequest();
		
		String uid = request.getHeader("uid");
		String token = request.getHeader("token");
		String sysType = request.getHeader("sysType");
		
		ApiResult apiResult = null;
		
		if(StringUtils.isEmpty(token)) {
			apiResult = new ApiResult<>(CodeContant.TOKEN_NULL.getCode(), CodeContant.TOKEN_NULL.getMsg());
			
		}else if(StringUtils.isEmpty(sysType)) {
			apiResult = new ApiResult<>(CodeContant.SYSTYPE_NULL.getCode(), CodeContant.SYSTYPE_NULL.getMsg());
		}else if(StringUtils.isEmpty(uid)) {
			apiResult = new ApiResult<>(CodeContant.UID_NULL.getCode(), CodeContant.UID_NULL.getMsg());
		}else {
			apiResult = tokenService.verifyToken(uid, token, sysType);
		}

		if(apiResult.getCode()==1) {
			ctx.setSendZuulResponse(true);
			ctx.setResponseStatusCode(200);
		}else {
			ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(200);
            ctx.setResponseBody(JSON.toJSONString(apiResult));
            log.error("======== 操作异常： url=[{}] uid=[{}] token=[{}] sysType=[{}] params=[{}] result=[{}]",request.getRequestURL().toString(),uid,token,sysType,GetParamsUtil.getParams(ctx),apiResult.getMsg());
		}
		
		return null;
	}

	@Override
	public boolean shouldFilter() {
		boolean flag = true;
		if (tokenProperties != null) {
			
			if(tokenProperties.isEnable()) {
				RequestContext ctx = RequestContext.getCurrentContext();
				HttpServletRequest request = ctx.getRequest();
				
				// 按照配置项取消拦截
				if (tokenProperties.getNoInterceptUrl() != null
						&& !tokenProperties.getNoInterceptUrl().isEmpty()) {
					flag = !tokenProperties.getNoInterceptUrl().contains(request.getRequestURI());
				}
			}else {
				flag = false;
			}
			
        } 
		return flag;
	}

	@Override
	public int filterOrder() {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public String filterType() {
		// TODO Auto-generated method stub
		return "pre";
	}

}
